package com.lsl.rdf.interceptor;

import com.lsl.rdf.UnauthorizedException;
import com.lsl.rdf.UnexpectedException;
import com.lsl.rdf.constant.enums.CommonConstants;
import com.lsl.rdf.service.UserSupport;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

import static com.lsl.rdf.constant.enums.CommonConstants.USER_ID_HEADER_ATTR;

/**
 * Created by lsl on 2021/4/16.
 */
@Slf4j
public class UserAuthenticationInterceptor implements HandlerInterceptor {

    private UserSupport userSupport;

    public UserAuthenticationInterceptor(UserSupport userSupport) {
        this.userSupport = userSupport;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        return checkToken(request);
    }

    /**
     * 验证token
     *
     * @param request request
     * @return bool
     */
    private boolean checkToken(HttpServletRequest request) {
        if (Objects.isNull(request)) {
            log.error("UserAuthenticationInterceptor request is null");
            throw new UnexpectedException("获取token失败");
        }
        String accessToken = request.getHeader(CommonConstants.ACCESS_TOKEN_HEADER_ATTR);
        if (StringUtils.isBlank(accessToken) || accessToken.length() != 36) {
            throw new UnauthorizedException("无效token");
        }
        Long userId = userSupport.getToken(accessToken);
        if (Objects.isNull(userId)) {
            return false;
        }
        request.setAttribute(USER_ID_HEADER_ATTR, userId);
        return true;
    }
}
